#include "key.h"
#include "gpio.h"
#include "timer.h"

// 定义按键变量
KEY keys[2];

// 定义按键引脚
#define KEY_GPIO_1  GPIO_PIN_13
#define KEY_GPIO_2  GPIO_PIN_23

// 按键初始化,并且采用定时中断去扫描按键的状态
void KEY_Init(void)
{
    TIM_Init(Timer3,10);
    GPIO_Init(KEY_GPIO_1,INPUT_PULLUP);
    GPIO_Init(KEY_GPIO_2,INPUT_PULLUP);
}

// 按键菜单逻辑
// SW1按键作为使能按键，短按启动，长按重置SW2
// SW2按键作为任务选择按键，根据按键的次数决定要执行哪个任务，一旦超过这个数字后就进行循环从头开始

// 按键扫描
void KEY_Scan(void)
{
	keys[0].keyState = GPIO_ReadPin(KEY_GPIO_1);
	keys[1].keyState = GPIO_ReadPin(KEY_GPIO_2);

	for(uint8_t i = 0;i < 2;i++)
	{
		if(keys[i].keyJudge == 0)
		{
			keys[i].keyTim = 0;

			if(keys[i].keyState == LOW)
			{
				keys[i].keyJudge = 1;
			}
		}

		if(keys[i].keyJudge == 1)
		{
			if(keys[i].keyState == LOW)
			{
				keys[i].keyJudge = 2;
			}
			else
			{
				keys[i].keyJudge = 0;
			}
		}

		if(keys[i].keyJudge == 2)
		{
			if(keys[i].keyState == LOW)
			{
				keys[i].keyTim++;
		
				if(keys[i].keyTim >= 100)      // 10ms *100 = 1s
				{
					keys[i].keyLong = 1;
					keys[i].keyJudge = 3;      
				}
			}
			else                              
			{
				keys[i].keySingle = 1;
				keys[i].keyJudge = 0;
			}
		}

		if(keys[i].keyJudge == 3)
		{
			if (keys[i].keyState == HIGH)
			{
				keys[i].keyJudge = 0;
			}
		}
	}
}

// 中断中处理按键扫描
void TIM_Interrupt_3(void)
{
    KEY_Scan();
}